package day13.thread02;


/**
 * @author Xiao
 * @date 2021/8/5
 */
public class Ticket3 implements Runnable{
    private static int ticketCount = 100;

    @Override
    public void run() {
        while (true) {
            //同步代码块
            if ("窗口1".equals(Thread.currentThread().getName())) {
                synchronized (Ticket3.class) {
                    if (ticketCount == 0) {
                        break;
                    }
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()
                            + "卖出了1张票，还剩" + --ticketCount + "张票。");
                }
            }
            if ("窗口2".equals(Thread.currentThread().getName())) {
                //同步方法
                boolean result = synchronizedMethod();
                if (result) {
                    break;
                }
            }
        }
    }

    private static synchronized boolean synchronizedMethod() {
        if (ticketCount == 0) {
            return true;
        }
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()
                + "卖出了1张票，还剩" + --ticketCount + "张票。");
        return false;
    }
}
